package lab4Questions;

import java.io.*;
import java.security.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;




public class ReturnDigest extends Thread {

  private File input;
  private byte[] digest;
  private ReentrantReadWriteLock  rwl;
  private Lock l;

  public ReturnDigest(File input) {
   this.input = input; 
   this.rwl = new ReentrantReadWriteLock ();
   this.l = rwl.readLock();
  }

  public void run() {
    try {
      this.l.lock();
      FileInputStream in = new FileInputStream(input);
      MessageDigest sha = MessageDigest.getInstance("SHA");
      DigestInputStream din = new DigestInputStream(in, sha);
      int b;
      while ((b = din.read()) != -1) ;
      din.close();
      digest = sha.digest();
    }
    catch (IOException e) {
      System.err.println(e);
    }
    catch (NoSuchAlgorithmException e) {
      System.err.println(e);
    }
    finally{
    	this.l.unlock();
    }
    
  }
    
  
  public byte[] getDigest() throws InterruptedException {
	  if(this.l.tryLock(1L, TimeUnit.SECONDS))
		  return digest;
	  else
		  return null;
  }

}
